package com.sx.zongzhi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.PhotoBean;
import com.sx.zongzhi.bean.UserBean;
import com.sx.zongzhi.net.ServiceFactory;
import com.sx.zongzhi.presenter.UpdatePersonInfoPest;
import com.sx.zongzhi.presenter.UploadFilePest;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.UploadFileView;
import com.sx.zongzhi.voiceamr.UpdatePersonView;
import com.sx.zongzhi.widget.LoadDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

/**
 * @desc: 个人信息
 */
public class PersonInformationActivity extends BaseActivity implements UpdatePersonView, UploadFileView {

    @BindView(R.id.iv_picture)
    ImageView ivPicture;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;

    private IDataStorage dataStorage;
    private UserBean userBean;
    private String name = "",phone = "",path = "",userID ="";

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_person_information);
        ButterKnife.bind(this);
        setTitleName("个人信息");
        setTitleRight(R.string.submit);

        dataStorage = DataStorageFactory.getInstance(
                this, DataStorageFactory.TYPE_DATABASE);
        if (dataStorage.contains(UserBean.class,getPackageName())){
            userBean = dataStorage.load(UserBean.class,getPackageName());
            userID = userBean.getId();
            etName.setText(userBean.getName());
            etPhone.setText(userBean.getMobile());
            RequestOptions options = new RequestOptions().centerCrop()
                    .placeholder(R.mipmap.head_default)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .circleCrop()
                    .error(R.mipmap.head_default);
            Glide.with(this)
                    .load(ServiceFactory.NEW_API_BASE_URL+ File.separator + userBean.getHeaderUrl())
                    .apply(options)
                    .into(ivPicture);
        }
    }

    @OnClick({R.id.tv_right, R.id.rl_headPortrait})
    public void OnClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_right:
                name = etName.getText().toString().trim();
                phone = etPhone.getText().toString().trim();
                if (name.equals(userBean.getName())&&phone.equals(userBean.getMobile())&&BaseUtil.isEmpty(path)){
                    ToastUtils.showToast(this,"提交失败");
                    return;
                }
                if (BaseUtil.isEmpty(name)){
                    etName.setError("名字不能为空");
                    return;
                }

                if (BaseUtil.isEmpty(phone)||!BaseUtil.isMobile(phone)){
                    etPhone.setError("请填写正确的手机号");
                    return;
                }
                LoadDialog.show(PersonInformationActivity.this,"修改中...");
                if (!BaseUtil.isEmpty(path)){
                    List<File> files = new ArrayList<>();
                    files.add(new File(path));
                    new UploadFilePest(this).uploadFile(this,files);
                }else {
                    new UpdatePersonInfoPest(this).updatePerson(PersonInformationActivity.this,userID,name,phone,"");
                }
                break;
            case R.id.rl_headPortrait:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .maxSelectNum(1)
                        .previewImage(true)// 是否可预览图片
                        .withAspectRatio(1,1)
                        .enableCrop(true)
                        .compress(true)
                        .compressGrade(Luban.CUSTOM_GEAR)
                        .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
           if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                if (!picUrls.isEmpty()) {
                    for (LocalMedia localMedia : picUrls) {
                        path = localMedia.getCompressPath();
//                        path = localMedia.getPath();
                        RequestOptions options = new RequestOptions().centerCrop()
                                .placeholder(R.mipmap.head_default)
                                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                                .circleCrop()
                                .error(R.mipmap.head_default);
                        Glide.with(this)
                                .load(path)
                                .apply(options)
                                .into(ivPicture);
                    }
                }
            }
        }
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(PersonInformationActivity.this);
        ToastUtils.showToast(PersonInformationActivity.this,message);
    }

    @Override
    public void updatePersonSuccess(UserBean userBeans) {
        LoadDialog.dismiss(PersonInformationActivity.this);
        userBean.setName(userBeans.getName());
        userBean.setMobile(userBeans.getMobile());
        userBean.setHeaderUrl(userBeans.getHeaderUrl());
        dataStorage.storeOrUpdate(userBean,getPackageName());
        MyRxBus.get().post(new MsgEvent<>("MyFragment",1,userBean));
        ToastUtils.showToast(PersonInformationActivity.this,"修改成功");
    }

    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
        String paths = "";
        for (PhotoBean photoBean : beans){
            paths = photoBean.getPath();
        }
        new UpdatePersonInfoPest(this).updatePerson(PersonInformationActivity.this,userID,name,phone,paths);
    }
}
